// users.js
const router = require('koa-router')();
const users = require('../models/users');
const jwt = require('jsonwebtoken');

router.prefix('/users');

router.post('/register', function *() {
  const { username, password } = this.request.body;
  const result = users.register(username, password);
  this.body = result;
});

router.post('/login', function *() {
  const { username, password } = this.request.body;
  const result = users.login(username, password);
  if (result.status === 0) {
    const token = jwt.sign({ id: result.user.id }, 'your_secret_key');
    this.body = { status: 0, msg: 'User logged in successfully', token };
  } else {
    this.body = result;
  }
});

module.exports = router;